import { init } from 'snabbdom/build/package/init'
import {classModule} from 'snabbdom/build/package/modules/class'
import {propsModule} from 'snabbdom/build/package/modules/props'
import {styleModule} from 'snabbdom/build/package/modules/style'
import {eventListenersModule} from 'snabbdom/build/package/modules/eventlisteners'
import {h} from 'snabbdom/build/package/h'

let patch = init([eventListenersModule])

let list = [
  {
    id: 1,
    title: 'bbb',
    description: 'akdjfldsjfldjflsjlfjdslkfjdlf'
  },
  {
    id: 2,
    title: 'Aaa'
  }
]
let vnode = null

function addMovie () {
  list.push({
    id: list.length + 1,
    title: 'xxxx',
    description: 'xxxxxxxxxxxxx'
  })
  vnode = patch(vnode, view())
}

function rankByTitle() {
  list = list.sort((a, b) => {
    if (a.title > b.title) {
      return 1
    }
    if (a.title < b.title) {
      return -1
    }
    return 0
  })
  vnode = patch(vnode, view())
}

function deleteItem(item) {
  console.log(item)
  list.splice(item.id - 1, 1)
  node = patch(vnode, view())
}

function view() {
  let view = [
    h('h1', 'movie'), 
    h('button', { on: { click: addMovie } }, 'add'),
    h('button', { on: { click: rankByTitle } }, 'rankByTitle'),
    h('ul', list.map(item => {
      return h('li', [
        h('span', item.id),
        h('span', item.title),
        h('span', item.description),
        h('button', { on: { click: [deleteItem, item] }}, 'delete')
      ])
    }))
  ]
  return h('div', view)
}

function render () {
  const container = document.getElementById('container')
  vnode = patch(container, view())
}
window.addEventListener('DOMContentLoaded', () => {
  render()
})